/**
 * 线下入款js
 * by karl
 */
//最高金额
var upMoney = parseFloat(1000000);
//最低金额
var dwMoney = parseFloat(50);
//优惠次数 类型 0 -首次 1 -每次
var discountTimes = 1;
//优惠百分比
var percentageDiscount = 0.99;
//稽核优惠标准
var auditDiscountStandard = 0.99;
//打码倍数
var codeMultiple = 1;
//是否放弃存款优惠
var preDepositStatusOnline = 0;
//已经优惠次数
var haveDiscountTimes = 0;
//优惠系数 -次数
var preRatioOnline = 0.99;
//优惠上限金额
var preUp = 100;
//限制不允许一直提交
var issubmit  = 0;
//收款帐号Id
var rbankId;
//入款银行名称
var companyBankName;
//入款银行Id
var companyBankId;
//优惠的状态值
var isyouhui = 1;
//扫码类可显示的快选金额个数
var scanFastMoneyCount = 0;
//转账类可显示的快选金额个数
var transferFastMoneyCount = 0;
//是否显示扫描码
var	isScanShow=false;
var	isDirectShow=false;
var isShowTransferFastSelectMoney=false;
var transferIncomeName="";
var transferPlaceholder="ID";
$(function () {
	//获取当前时间
	var crtTime = new Date();
    //设置时间
    $('#time').val(dateFtt("yyyy-MM-dd hh:mm:ss",crtTime));
    //支付类型，默认选中0代表扫码，1代表转账
    var payType = $("#payType").val();
    if(isScanShow) {
    	scanFastMoneyCount = showFastSelectMoney($("#scanMoneyDetails"),isShowScanFastSelectMoney,scanFastSelectMoney1,scanFastSelectMoney2,scanFastSelectMoney3,scanFastSelectMoney4,scanFastSelectMoney5);
    }
    if(isDirectShow) {
    	transferFastMoneyCount = showFastSelectMoney($("#transferMoneyDetails"),isShowTransferFastSelectMoney,transferFastSelectMoney1,transferFastSelectMoney2,transferFastSelectMoney3,transferFastSelectMoney4,transferFastSelectMoney5);
    }
    //当扫码不存在好友转账存在时做处理
    if (!isScanShow && isDirectShow) {
        $("#transferAccountTab").addClass('active');
        $("#transferAccount").show();
        $('#scanMoneyDetails').hide();
        $('#transferMoneyDetails').show();
        //扫码文案隐藏，转账文案显示
        $('#scanDepositContext').hide();
        $('#directDepositContext').show();
        //当只有好友转账时设置参数为1
        payType = 1;
        $("#payType").val(1);
    }
    if (!isScanShow) {
        $("#scanPic").hide();
        $("#scanPicTab").hide();
        $("#transferAccountTab").addClass('active');
    }
    if (!isDirectShow) {
        $("#transferAccount").hide();
        $("#transferAccountTab").hide();
        $("#scanPicTab").addClass('active');
    }
    
	if(payType == 0){
		if(isShowScanFastSelectMoney == 1) {
        	$('#scanMoneyDetails').show();
        } else {
        	$('#scanMoneyDetails').hide();
        }
        $('#transferMoneyDetails').hide();
        $("#incomeName").html(scanIncomeName);
        $("#nickName").attr("placeholder", "请务必填写您转账的" + scanPlaceholder);
		$('[name="scanRadio"]').eq(0).click();
        if (!$('[name="scanRadio"]').length) {
            $('#subs').remove();
        }
	}else{
		$('#scanMoneyDetails').hide();

		if(isShowTransferFastSelectMoney == 1) {
        	$('#transferMoneyDetails').show();
        } else {
        	$('#transferMoneyDetails').hide();
        }
        $("#incomeName").html(transferIncomeName);
        $("#nickName").attr("placeholder", "请务必填写您转账的" + transferPlaceholder);
	    $('[name="transferRadio"]').eq(0).click();
	    if (!$('[name="transferRadio"]')) {
	        $('#subs1').hide();
	    }
	}
	
	if(!scanFastMoneyCount || scanFastMoneyCount == 0) {
		$('#scanMoneyDetails').hide();
	}
	if(!transferFastMoneyCount || transferFastMoneyCount == 0) {
		$('#transferMoneyDetails').hide();
	}
	
	//通过次数范围控制显示
    if (0 == discountTimes) {
        //首次
        if (0 != haveDiscountTimes) {
            $('#applydiscountLi').hide();
            $('#applydiscount_id').find("option[value='2']").attr("selected", true);
        }
    } else if (1 == discountTimes) {
        //非首次
        if (preRatioOnline < parseInt(haveDiscountTimes) + 1) {
            $('#applydiscountLi').hide();
            $('#applydiscount_id').find("option[value='2']").attr("selected", true);
        }
    }

    if (0 == preDepositStatusOnline) {
        //不可放弃优惠 默认选中优惠  不可选
        $('#applydiscount_id').find("option[value='1']").attr("selected", true);
        $('#applydiscount_id').attr("disabled", true);
        $('#applydiscount_id').css('background', '#A9A9A9');
    }
})

/**
 * 支付优惠
 */
var reg = /^\d+\.?\d{0,2}$/;
p3AmtChange = function(){
	var money = $('#payMoney').val();
    if (money == "" || isNaN(money)) {
        $('#amtid').html('&nbsp;请您输入充值金额');
        return;
    } else {
        var yhMoney = (money * parseFloat(percentageDiscount) / 100);
        var codeMultipleNum = codeMultiple;
        if (0 == parseInt(discountTimes)) {
            //首次
            if (0 == parseInt(haveDiscountTimes)) {
                if (preUp <= yhMoney) {
                    yhMoney = preUp;
                }
                yhMoney = parseFloat(round2(yhMoney, 2));
                if (money >= parseFloat(auditDiscountStandard)) {
                    if (money >= (upMoney + 0.0001)) {
                        yhMoney = (upMoney * parseFloat(percentageDiscount) / 100);
                    }
                    if (preUp <= yhMoney) {
                        yhMoney = preUp;
                    }
                    yhMoney = round2(yhMoney, 2);
                } else {
                    yhMoney = 0;
                }
            } else {
                yhMoney = 0;
            }
            $('#codeMultipleId').html("(优惠" + yhMoney + "，" + codeMultipleNum + "倍打码)");
        } else if (1 == parseInt(discountTimes)) {
            //每次
            if (money >= parseFloat(auditDiscountStandard)) {
                //次数小于优惠系数
                if (preRatioOnline >= parseInt(haveDiscountTimes) + 1) {
                    if (money >= (upMoney + 0.0001)) {
                        yhMoney = (upMoney * parseFloat(percentageDiscount) / 100);
                    }
                    if (preUp <= yhMoney) {
                        yhMoney = preUp;
                    }
                    yhMoney = round2(yhMoney, 2);
                } else {
                    yhMoney = 0;
                }
            } else {
                yhMoney = 0;
            }
            $('#codeMultipleId').html("(优惠" + yhMoney + "，" + codeMultipleNum + "倍打码)");
        }
    }


    if (money === "" || isNaN(money)) {
        $('#amtid').html('&nbsp;请您输入充值金额');
        return;
    }
    if (!reg.test(money)) {
        $('#amtid').html('&nbsp;请您输入充值金额');
        return;
    }
    if ((dwMoney - 0.0001) >= money) {
        $('#amtid').html('&nbsp;最低金额' + dwMoney);
        return;
    }
    if (money >= (upMoney + 0.0001)) {
        $('#amtid').html('&nbsp;最高金额' + upMoney);
        return;
    }
}
$('#payMoney').keyup(function () {
	p3AmtChange();
});

/**
 * 点击后切换当前时间
 */
$('#time').click(function () {
	//获取当前时间
	var crtTime = new Date();
    $('#time').val(dateFtt("yyyy-MM-dd hh:mm:ss",crtTime));
});

/**
 * 二维码切换当前选中的参数
 * @param BankName
 * @param rban
 * @param BankId
 * @param chamberlain
 */
function selectScan(bankName, rban, bankId, chamberlain) {
    companyBankName = bankName; //获取微信扫码 账号name
    companyBankId = bankId;
    //设置入款银行Id
    rbankId = rban;
    //如果银行为空时隐藏收款人帐号
    if (bankName == null || bankName == '') {
        $('#payAccountShow').hide();
    } else {
        $('#payAccountShow').show();
    }
    //收款人帐号赋值
    $('#payAccount').val(bankName);
    $('#payAccount').css('background', '#A9A9A9');
    $('#chamberlain').val(chamberlain);
    //切换扫码时默认设置
    $('#payAccountSpan').html('<span style="color: red">*</span>收款人'+payName+'账号');
}

/**
 * 好友转账切换方法
 * @param name
 * @param rban
 * @param BankId
 * @param chamberlain
 * @param onlineBankAccount
 * @param onlineBankName
 */
function selectAccount(name, rban, BankId, chamberlain,onlineBankAccount,onlineBankName) {
	//好友转账默认显示
	$('#payAccountShow').show();
	//当前支付的名称
	if(onlineBankAccount){//如果银行帐号不为空的话则显示收款人银行
		$('#payAccount').val(onlineBankAccount);
		$('#payAccountSpan').html('<span style="color: red">*</span>收款人银行账号')
		$('#payAccount').css('background','#A9A9A9');
		$('#trans1').css('display','none');
		$('#trans2').css('display','inline-block');
        $('#chamberlain').val(chamberlain);
        $('#onlineBankNameValue').val(onlineBankName);//用于后台显示入款的银行使用
        rbankId = rban;
        companyBankId = BankId;
	}else if(name){
        $('#payAccount').val(name);
        $('#payAccountSpan').html('<span style="color: red">*</span>收款人'+payName+'账号')
        $('#payAccount').css('background','#A9A9A9');
        $('#trans1').css('display','inline-block');
		$('#trans2').css('display','none');
        $('#chamberlain').val(chamberlain);
        $('#onlineBankNameValue').val('');
        rbankId = rban;
        companyBankId = BankId;
    }
	bankId = BankId;
	console.log(rbankId)
}

/**
 * 切换标签方法
 */
$('#paytab li').click(function () {
    $('#paytab li').removeClass('active');
    $(this).addClass('active');
    var index = $(this).attr('index');
    
    //1:显示扫码,2:好友转账
    if (index == 1) {
        $('#scanPic').show();
        if(isShowScanFastSelectMoney == 1 && scanFastMoneyCount && scanFastMoneyCount > 0) {
        	$('#scanMoneyDetails').show();
        } else {
        	$('#scanMoneyDetails').hide();
        }
        $('#transferMoneyDetails').hide();
        $('#transferAccount').hide();
        $("#incomeName").html(scanIncomeName);
        $("#nickName").attr("placeholder", "请务必填写您转账的" + scanPlaceholder);
        //设置默认选中第一个
        $('[name="scanRadio"]').eq(0).click();
        if (!$('[name="scanRadio"]').length) {
            $('#subs').remove();
        }
        //选中扫码时设置为0
        $("#payType").val(0);
        //转账文案隐藏，扫码文案显示
        $('#directDepositContext').hide();
        $('#scanDepositContext').show();
    } else {
        $('#scanPic').hide();
        $('#transferAccount').show();
        $('#scanMoneyDetails').hide();
        if(isShowTransferFastSelectMoney == 1 && transferFastMoneyCount && transferFastMoneyCount > 0) {
        	$('#transferMoneyDetails').show();
        } else {
        	$('#transferMoneyDetails').hide();
        }
        $("#incomeName").html(transferIncomeName);
        $("#nickName").attr("placeholder", "请务必填写您转账的" + transferPlaceholder);
        //设置默认选中第一个
        $('[name="transferRadio"]').eq(0).click();
	    if (!$('[name="transferRadio"]')) {
	        $('#subs1').hide();
	    }
	    //选中好友转账时设置为1
	    $("#payType").val(1);
	    //扫码文案隐藏，转账文案显示
        $('#scanDepositContext').hide();
        $('#directDepositContext').show();
    }

})

/**
 * 支付提交函数
 */
function submitBank(){
	var options = {};
	if (issubmit == 1) {
		alert("服务器正在处理您的信息,请耐心等待!!");
		return false;
	}
	//支付类型，默认选中0代表扫码，1代表转账，不同的支付类型取值不一样
    var payType = $("#payType").val();
    //获取支付的类型
    var way = getPayWay(parseInt(bankId),payType);
    //昵称
    var nickName = $('#nickName').val();
    //存入金额
    var amount = $('#payMoney').val();
    //当前存入时间
    var time = $('#time').val();
    //当前选择的厅主银行卡帐号用户名
    var chamberlain = $('#chamberlain').val();
    //用于微信银行转账银行显示使用
    var onlineBankNameValue = $('#onlineBankNameValue').val();
    //是否选择优惠 begin
    var isyouhui = 1;
    var applydiscount = 1;
    var yhmoney = '';
    applydiscount = $('#applydiscount_id').val();
    yhmoney       = $('#codeMultipleId').text();
    if (yhmoney.indexOf("优惠0") > 0 && !yhmoney.indexOf("优惠0.") > 0) {
        isyouhui = 0;
    } else {
        if (1 == applydiscount) {
            //申请优惠
            isyouhui = 1;
        } else {
            //不申请优惠
            isyouhui = 0;
        }
    }
    options.isyouhui = isyouhui;
    //是否优惠 end
    
    //云闪付不需要昵称
    if(bankId != 25 && bankId != 26){
    	var nicheng = payType == 0 ? "请您输入" + scanPlaceholder : "请您输入" + transferPlaceholder;
    	if (!nickName) {
    		return alert(nicheng)
    	}
    	if (nickName.length > 30) {
    		return alert(payName+'昵称最大长度不能超过30位')
    	}
    }
    
    if (!time) {
        return alert('请填写:入款时间')
    }

    if (isNaN(amount) || amount == '') {
        alert('请您输入充值金额');
        return false;
    }
    if ((dwMoney - 0.0001) >= amount || amount >= (upMoney + 0.0001)) {
        alert("您输入的金额有误");
        return;
    }
    options = {
        'actionType': 'submit',
        'mytime': time,
        'name': nickName,
        'amount': amount,
        'companyBankName': chamberlain, //收款名称 微信二维码 账户名称
        'companyBankId': companyBankId, //账户id
        'orderno': orderno,//单号是统一的
        'rbankid': rbankId,
        'isyouhui': isyouhui,
        'fromBank': bankId,
        'way': way, //存款方式
        'bankAddress':onlineBankNameValue
    };
    
    $.ajax({ // 提交存款信息
        type: 'POST',
        url: ctx + '/pay/BankPayMerchantSerlvet',
        data: options, // 2种方式 参数不一样
        dataType: 'json',
        success: function (__res) {
            if (__res.success) {
                //后台新增了会员返回类型,如果是测试会员则,直接提示入款成功
				if(__res.memType=='98'){
					alert('入款成功!');
				}else{
					alert('提交申请成功，财务将在1-3分钟内为您添加额度，请稍候！');
				}
//                $('#depositeAera').hide();
                var auditingStatus;
                try {
                    auditingStatus = window.opener.auditingStatus.value;
                } catch (e) {
                }
                if (auditingStatus == null  || !auditingStatus) {
                    try {
                        auditingStatus = window.dialogArguments.document.getElementById("auditingStatus").value;
                    } catch (e) {
                    }
                }
                if (auditingStatus == null) {
                    try {
                        auditingStatus = parent.document.getElementById("auditingStatus").value;
                    } catch (e) {
                    }
                }
                if(auditingStatus == 1){
	        		window.opener.selectHotelChrome(); 
				}else{
				    //调用父级 函数 恢复存款初始页面
                    window.parent.QSFUN.MChgPager({method: 'bankSavings'});
				}
                window.close();
            } else {
            	if(__res.msg && __res.msg == "抱歉，支付失败，请重试") {
            		alert(__res.msg);
            		window.top.location.reload();
            	} else {
            		alert(__res.msg + ',提交失败，请联系客服！');
            	}
            }
        },
        error: function (a, b, c) {
            alert('服务器正忙,不能及时处理您的信息,请稍候再试！');
        },
        complete: function () {
            issubmit = 0;
        }
    });
}

/**
 * 金额输入时的校验函数
 * @param obj
 */
function clearNoNum(obj) {
    var reg   = /^\d+\.?\d{0,2}$/;
    var money = obj.value;
    var id    = obj.id;
    var amtid = "amtid";
    if (id == 'payMoney') {
        amtid = "amtid";
    }
    if (money === "" || isNaN(money)) {
        $('#' + amtid).html('&nbsp;请您输入充值金额');
        obj.value = "";
        return;
    }
    if (!reg.test(money)) {
        $('#' + amtid).html('&nbsp;请您输入充值金额');
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
        return;
    }

	obj.value = obj.value.trim(); // 去掉空格
    if (obj.value !== '') { // 去掉前缀多出的0
    	var nmArr = obj.value.split('.');
    	if (nmArr[0] !== '') {
    		nmArr[0] = Number(nmArr[0]);
    	}
    	obj.value = nmArr.join('.')
    }
    money = obj.value
    if ((dwMoney - 0.0001) >= money) {
        $('#' + amtid).html('&nbsp;最低金额' + dwMoney);
        return;
    }
    if (money >= (upMoney + 0.0001)) {
        $('#' + amtid).html('&nbsp;最高金额' + upMoney);
        return;
    }
    $('#' + amtid).html('');
}

//刷新图片重新加载
function refreshImg(comp) {
    if($(comp).hasClass('lodingpic')) return false;
    var compValue = $(comp).attr("value");
    var imgSrc = $("#"+compValue).attr("src");

    $("#"+compValue).attr("src",imgSrc);
    
    $(comp).addClass('lodingpic');
    
    setTimeout(function(){
        $(comp).removeClass('lodingpic');
    },700)
}

//复制内容到粘贴板
function copyData (data) {
	var oInput = document.createElement('input');
    oInput.value = data;
    // 避免IE浏览器弹出咨询框的时候文本框显示在页面上
    oInput.style.setProperty('position', 'absolute', 'important');
    oInput.style.setProperty('top', '-1000px', 'important');
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    oInput.className = 'oInput';
    oInput.style.display='none';
    Toast('复制成功', 300);
}

/**
 * 弹出框
 * @param fmt
 * @param date
 * @returns
 */
function openWin(url, open, iWidth, iHeight) {
    //获得窗口的垂直位置
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    //获得窗口的水平位置
    window.open(url, open, 'height=' + iHeight + ',,innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=300,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
}

/**
 * 复制成功后的提示框
 */
function Toast(msg,duration){
    duration=isNaN(duration)?300:duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText="width: 25%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;top: 25%;left: 30%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;";
    document.body.appendChild(m);
    setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function() { document.body.removeChild(m) }, d * 1000);
    }, duration);
}

/**************************************时间格式化处理************************************/
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

/**
 * 判断是否为空格
 */
function isBlank(str) {
    if (str == "") return true;
    var regu = "^[ ]+$";
    var re   = new RegExp(regu);
    return re.test(str);
}

/**
 * 数字格式化 2位
 * author: adaf
 */
function round2(v, e) {
    var d = parseFloat(v);
    if (isNaN(d)) d = 0.0;
    return d.toFixed(2);
}

/**
 * 获取当前选择的支付方式的支付类型
 * way 
 *  8:微信扫码,  9:微信转账
 *  5:支付宝扫码,10:支付宝转账
 * 11:QQ扫码,  12:QQ转账
 * 13:财付通扫码,14:财付通转账
 * 16:云闪付扫码,15:云闪付转账
 */
function getPayWay(bankId,bankType){
	switch (bankId) {
	    case 17://支付宝扫码
	    	return 5;
	    case 18://支付宝转账
	    	return 10;
	    case 19://微信扫码
	    	return 8;
	    case 20://微信转账
	    	return 9;
	    case 21://QQ扫码
	    	return 11;
	    case 22://QQ转账
	    	return 12;
	    case 23://财付通扫码
	    	return 13;
	    case 24://财付通转账
	    	return 14;
	    case 25://云闪付扫码
	    	return 16;
	    case 26://云闪付转账
	    	return 15;
	}
}

function showFastSelectMoney(moneyDetailDiv, isShowFastSelectMoney, fastSelectMoney1, fastSelectMoney2, fastSelectMoney3, fastSelectMoney4, fastSelectMoney5) {
	if(isShowFastSelectMoney && isShowFastSelectMoney == 1) {//如果需要显示快选金额，则获取具体快选金额属性
		//快选金额列表
		var moneyList = [];
		if(fastSelectMoney1 && fastSelectMoney1 >= dwMoney && fastSelectMoney1 <= upMoney) {
			moneyList.push(parseInt(fastSelectMoney1));
		}
		if(fastSelectMoney2 && fastSelectMoney2 >= dwMoney && fastSelectMoney2 <= upMoney) {
			moneyList.push(parseInt(fastSelectMoney2));
		}
		if(fastSelectMoney3 && fastSelectMoney3 >= dwMoney && fastSelectMoney3 <= upMoney) {
			moneyList.push(parseInt(fastSelectMoney3));
		}
		if(fastSelectMoney4 && fastSelectMoney4 >= dwMoney && fastSelectMoney4 <= upMoney) {
			moneyList.push(parseInt(fastSelectMoney4));
		}
		if(fastSelectMoney5 && fastSelectMoney5 >= dwMoney && fastSelectMoney5 <= upMoney) {
			moneyList.push(parseInt(fastSelectMoney5));
		}
		//对 快选金额数组进行升序排序
		if(moneyList.length > 0) {
			moneyList.sort(function(a,b){
				if(a > b) {
					return 1;
				} else if(a < b) {
					return -1
				} else {
					return 0;
				}    
			});
			for(var i = 0; i < moneyList.length; i++) {
				var spanEle = $("<span class='fastSelectMoney'>" + moneyList[i] + "</span>");
				$(moneyDetailDiv).children().eq(1).append($(spanEle));
				$(spanEle).click(function(){
					$("#payMoney").val($(this).html());
					$(".fastSelectMoney").removeClass("moneySelected");
					$(this).addClass("moneySelected");
					p3AmtChange();
				});
			}
		}
		return moneyList.length;
	}
}